package com.hengby.hengcrud.config.mybatisplus;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.baomidou.mybatisplus.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.hengby.hengcrud.config.datasource.DruidProperties;
import com.hengby.hengcrud.config.mutidatasource.DynamicDataSource;
import com.hengby.hengcrud.config.mutidatasource.MutiDataSourceProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.hengby.hengcrud.core.common.status.DatasourceEnum.DATA_SOURCE_MASTER;
import static com.hengby.hengcrud.core.common.status.DatasourceEnum.DATA_SOURCE_SLAVE;

/**
 * @author zhouheng
 */
@Configuration
@EnableTransactionManagement(order = 2)//由于引入多数据源，所以让spring事务的aop要在多数据源切换aop的后面
@MapperScan(basePackages = {"com.hengby.hengcrud.modular.*.mapper"})
public class MybatisPlusConfig {
    @Autowired
    DruidProperties druidProperties;

    @Autowired
    MutiDataSourceProperties mutiDataSourceProperties;

    // 数据源配置 masterDataSource
    DruidDataSource masterDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidProperties.config(druidDataSource);

        return druidDataSource;
    }

    // 数据源配置 slaveDataSource
    DruidDataSource slaveDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        mutiDataSourceProperties.config(druidDataSource);
//        druidProperties.config(druidDataSource);
        return druidDataSource;
    }

    // 单数据配置
    @Bean
    @ConditionalOnProperty(prefix = "heng_crud",value = "muti-datasource-open", havingValue = "false")
    public DruidDataSource singleDatasource(){
        return masterDataSource();
    }

    // 多数据源配置
    @Bean
    @ConditionalOnProperty(prefix = "heng_crud",value = "muti-datasource-open", havingValue = "true")
    public DynamicDataSource mutiDatasource(){
       DruidDataSource dataSource1 = masterDataSource();
       DruidDataSource dataSource2 = slaveDataSource();

        try {
            dataSource1.init();
            dataSource2.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDefaultTargetDataSource(dataSource2);
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DATA_SOURCE_MASTER,dataSource1);
        targetDataSources.put(DATA_SOURCE_SLAVE, dataSource2);

        dynamicDataSource.setTargetDataSources(targetDataSources);
        return dynamicDataSource;
    }

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
        return paginationInterceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new MyMetaObjectHandler();
    }

    /**
     * 注入主键生成器
     */
    @Bean
    public IKeyGenerator keyGenerator(){
        return new H2KeyGenerator();
    }

    /**
     * 注入sql注入器
     */
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }

}
